package net.funtip.jdbc.driver;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;

import javax.sql.DataSource;


public class LogDataSource implements DataSource {

	protected static Logger log = Logger.getLogger(LogDataSource.class.getName());
	
	protected String url;
	protected String username;
	protected String password;
	protected Properties properties;
	protected int loginTimeout;
	protected PrintWriter logWriter = new PrintWriter(System.err);
	
	public LogDataSource(String url) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		this.url = url;
		log.finest("loading logDriver JDBC class");
		Class.forName("net.funtip.jdbc.driver.LogDriver");
	}

	public Connection getConnection() throws SQLException {
		Connection conn = null;
		if (username != null && password != null) {
			conn = DriverManager.getConnection(url,username,password);
		} else if (properties.size() > 0) {
			conn = DriverManager.getConnection(url, properties);
		} else {
			conn = DriverManager.getConnection(url);
		}
		return new FTConnection(conn);
	}

	public Connection getConnection(String username, String password) throws SQLException {
		Connection conn = DriverManager.getConnection(url,username,password);
		return new FTConnection(conn);
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public void setProperty(String key, String value) {
		this.properties.setProperty(key, value);
	}

	public int getLoginTimeout() {
		return loginTimeout;
	}

	public void setLoginTimeout(int loginTimeout) {
		this.loginTimeout = loginTimeout;
	}

	public PrintWriter getLogWriter() {
		return logWriter;
	}

	public void setLogWriter(PrintWriter logWriter) {
		this.logWriter = logWriter;
	}

	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		// TODO implement when using JDK 1.7
		return false;
	}

	public <T> T unwrap(Class<T> iface) throws SQLException {
		// TODO implement when using JDK 1.7
		return null;
	}

	public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
		// TODO implement when using JDK 1.7
		return null;
	}

}
